/**
 * 统一云对象请求封装
 * @param {string} objectName 云对象名称 如: 'client-wallpaper-classify'
 * @param {string} methodName 方法名
 * @param {object} params 请求参数
 * @param {object} config 配置项
 * @returns {Promise}
 */

// 缓存管理器
const cacheManager = {
  // 清除指定键的缓存
  clear: (key) => {
    try {
      uni.removeStorageSync(key);
      console.log(`[Cache] Cleared: ${key}`);
    } catch (e) {
      console.error('[Cache] Clear failed:', e);
    }
  },

  // 清除匹配模式的缓存
  clearByPattern: (pattern) => {
    try {
      const res = uni.getStorageInfoSync();
      let count = 0;
      res.keys.forEach(key => {
        if (key.includes(pattern)) {
          uni.removeStorageSync(key);
          count++;
          console.log(`[Cache] Cleared by pattern: ${key}`);
        }
      });
      console.log(`[Cache] Cleared ${count} items with pattern: ${pattern}`);
    } catch (e) {
      console.error('[Cache] Clear by pattern failed:', e);
    }
  },

  // 清除指定云对象的所有缓存
  clearObjectCache: (objectName) => {
    try {
      const res = uni.getStorageInfoSync();
      let count = 0;
      res.keys.forEach(key => {
        if (key.startsWith(`iss_cache/${objectName}/`)) {
          uni.removeStorageSync(key);
          count++;
          console.log(`[Cache] Cleared object cache: ${key}`);
        }
      });
      console.log(`[Cache] Cleared ${count} cache items for object: ${objectName}`);
    } catch (e) {
      console.error('[Cache] Clear object cache failed:', e);
    }
  },

  // 清除指定云对象方法的缓存
  clearMethodCache: (objectName, methodName) => {
    try {
      const res = uni.getStorageInfoSync();
      let count = 0;
      res.keys.forEach(key => {
        if (key.startsWith(`iss_cache/${objectName}/${methodName}/`)) {
          uni.removeStorageSync(key);
          count++;
          console.log(`[Cache] Cleared method cache: ${key}`);
        }
      });
      console.log(`[Cache] Cleared ${count} cache items for method: ${objectName}.${methodName}`);
    } catch (e) {
      console.error('[Cache] Clear method cache failed:', e);
    }
  },

  // 清除所有API缓存
  clearAllApiCache: () => {
    try {
      const res = uni.getStorageInfoSync();
      let count = 0;
      res.keys.forEach(key => {
        if (key.startsWith('iss_cache/')) {
          uni.removeStorageSync(key);
          count++;
          console.log(`[Cache] Cleared all API cache: ${key}`);
        }
      });
      console.log(`[Cache] Cleared ${count} API cache items`);
    } catch (e) {
      console.error('[Cache] Clear all API cache failed:', e);
    }
  },

  // 获取缓存数据（供调试用）
  getCacheData: (key) => {
    try {
      const cacheData = uni.getStorageSync(key);
      if (!cacheData) return null;
      
      const { data, expireTime } = cacheData;
      if (Date.now() > expireTime) {
        uni.removeStorageSync(key);
        return null;
      }
      return data;
    } catch (e) {
      console.error('[Cache] Get cache data failed:', e);
      return null;
    }
  }
};

function cloudRequest(objectName, methodName, params = {}, config = {}) {
  // 默认配置
  const defaultConfig = {
    showLoading: true,       // 是否显示加载提示
    loadingText: '加载中...', // 加载提示文字
    showError: true,         // 是否显示错误提示
    toLogin: false,          // 是否当有hasPermissionIssue问题时，将页面导向登录页面
    useCache: false,         // 是否使用缓存
    cacheKey: null,          // 缓存键名，默认自动生成
    cacheExpire: 3600,       // 缓存过期时间(秒)，默认1小时
    forceRefresh: false     // 是否强制刷新缓存
  };
  
  const mergedConfig = {...defaultConfig, ...config};
  
  // 生成缓存键名（使用路径式结构）
  const generateCacheKey = () => {
    // 基础路径
    const basePath = `iss_cache/${objectName}/${methodName}`;
    
    if (mergedConfig.cacheKey) {
      return `${basePath}/${mergedConfig.cacheKey}`;
    }
    
    // 生成基于参数的键名
    const paramsStr = JSON.stringify(params);
    // 缩短过长的参数字符串
    const shortParamsStr = paramsStr.length > 500 ? 
      paramsStr.substring(0, 500) + '...' + paramsStr.length : 
      paramsStr;
    
    // 创建安全的键名部分（替换特殊字符）
    const safeKeyPart = shortParamsStr
      .replace(/[^a-zA-Z0-9\-_]/g, '_')  // 替换非字母数字字符为下划线
      .replace(/_+/g, '_')               // 合并连续下划线
      .replace(/^_+|_+$/g, '');          // 去除首尾下划线
    
    return `${basePath}/${safeKeyPart}`;
  };

  // 获取缓存
  const getCache = (key) => {
    try {
      const cacheData = uni.getStorageSync(key);
      if (!cacheData) {
        console.log(`[Cache] No cache found for key: ${key}`);
        return null;
      }
      
      const { data, expireTime, timestamp } = cacheData;
      if (Date.now() > expireTime) {
        uni.removeStorageSync(key);
        console.log(`[Cache] Cache expired for key: ${key}`);
        return null;
      }
      console.log(`[Cache] Using cached data for key: ${key}, cached at: ${new Date(timestamp).toLocaleString()}`);
      return data;
    } catch (e) {
      console.error('[Cache] Get cache failed:', e);
      return null;
    }
  }

  // 设置缓存
  const setCache = (key, data) => {
    try {
      const expireTime = Date.now() + mergedConfig.cacheExpire * 1000;
      const cacheData = { 
        data, 
        expireTime, 
        timestamp: Date.now()
      };
      uni.setStorageSync(key, cacheData);
      console.log(`[Cache] Set cache for key: ${key}, expire at: ${new Date(expireTime).toLocaleString()}`);
    } catch (e) {
      console.error('[Cache] Set cache failed:', e);
    }
  }

  // 获取平台对应的登录页路径
  const getLoginUrl = () => {
    // #ifdef MP-WEIXIN
    return '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
    // #endif
    return '/uni_modules/uni-id-pages/pages/login/login-withpwd'
  }

  // 统一处理权限错误
  const handlePermissionError = (error, config) => {
    const errorInfo = error.detail || error
    let hasPermissionIssue = false
    let errorMsg = errorInfo.errMsg || '请求失败，请稍后重试'

    // 判断是否为权限错误
    if (errorInfo.errCode === 401 || 
        errorInfo.code === 401 || 
        errorInfo.errMsg?.includes('UNAUTHORIZED') || 
        errorInfo.errCode === 'TOKEN_EXPIRED') {
      hasPermissionIssue = true
      errorMsg = errorInfo.errCode === 'TOKEN_EXPIRED' ? '登录已过期，请重新登录' : '请先登录'
    }

    // 处理权限错误跳转
    if (hasPermissionIssue && config.toLogin) {
      uni.showModal({
        title: '提示',
        showCancel: false,
        content: errorMsg,
        success: () => {
          uni.navigateTo({ url: getLoginUrl() })
        }
      })
      return true // 表示已处理权限错误
    }

    // 显示普通错误提示
    if (config.showError) {
      uni.showToast({
        title: errorMsg,
        icon: 'none',
        duration: 3000
      })
    }

    return false
  }
  
  // 如果使用缓存且不强制刷新，先检查缓存
  if (mergedConfig.useCache && !mergedConfig.forceRefresh) {
    const cacheKey = generateCacheKey();
    const cachedData = getCache(cacheKey);
    if (cachedData) {
      return Promise.resolve(cachedData);
    }
  }

  return new Promise((resolve, reject) => {
    // 显示加载提示
    if (mergedConfig.showLoading) {
      uni.showLoading({
        title: mergedConfig.loadingText,
        mask: true
      })
    }
    
    // 获取云对象实例
    const cloudObject = uniCloud.importObject(objectName, {customUI: true})
    
    // 调用云对象方法
    cloudObject[methodName](params).then(res => {
      // 关闭加载提示
      if (mergedConfig.showLoading) {
        uni.hideLoading()
      }
      
      // 统一处理响应格式
      if (res && res.errCode === 0) {
        // 如果需要缓存，设置缓存
        if (mergedConfig.useCache) {
          const cacheKey = generateCacheKey();
          setCache(cacheKey, res.data);
        }
        resolve(res.data)
      } else {
        // 处理权限错误
        const isPermissionHandled = handlePermissionError(res, mergedConfig)
        
        reject({
          code: res?.code || 500,
          msg: res?.errMsg || '请求失败，请稍后重试',
          data: res?.data || null,
          handled: isPermissionHandled // 标记是否已处理权限错误
        })
      }
    }).catch(err => {
      // 关闭加载提示
      if (mergedConfig.showLoading) {
        uni.hideLoading()
      }
      
      // 处理权限错误
      const isPermissionHandled = handlePermissionError(err, mergedConfig)
      
      reject({
        code: err.errCode || 500,
        msg: err.errMsg || '网络请求失败',
        data: null,
        handled: isPermissionHandled // 标记是否已处理权限错误
      })
    })
  })
}

// 导出缓存管理器
export { cacheManager };

// 默认导出云请求方法
export default cloudRequest;